package cn.tedu.sp11.filter;

import cn.tedu.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //指定过滤器类型“pre”，“routes“，”post“，”error“
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }
    //指定过滤器添加的位置序号
    @Override
    public int filterOrder() {
        return 6;
    }
    //针对当前这次请求是否要指定过滤代码
    //如果请求item-service，指定全选判断
    //如果请求user 或 order，直接跳过过滤代码
    @Override
    public boolean shouldFilter() {
        //获取正在调用的服务的服务id
        RequestContext currentContext = RequestContext.getCurrentContext();
        String serviceId
                = (String)currentContext.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }
    //过滤代码
    @Override
    public Object run() throws ZuulException {
        
        //获取request对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //如果token参数不存在，阻止继续调用直接返回提示
        if(StringUtils.isBlank(token)){
            //阻止继续访问
            currentContext.setSendZuulResponse(false);
            //返回登录提示
            String not_login = JsonResult.err().code(JsonResult.NOT_LOGIN).msg("not login").toString();
            currentContext.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            currentContext.setResponseBody(not_login);
        }
        return null;//返回任何数据都无效..设计的时候就没设计这个东西
    }
}
